import os
import uuid
from datetime import datetime
from dataclasses import dataclass
from typing import Any, Dict, List

from flask import Flask, Response, jsonify, render_template, request, stream_with_context
import requests
from dotenv import load_dotenv

from llm_client import generate_consultation_reply


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def _ensure_env_loaded() -> None:
    """Load .env and any additional *.env* files in the project root as fallback.

    This allows using files like 'DEEPSEEK_API_KEY=xxxx.env.txt' without manual renaming.
    """
    # Load standard .env first
    load_dotenv(override=False)

    # If key not present, try to parse any file containing 'env' in name at root
    if not os.getenv("DEEPSEEK_API_KEY"):
        try:
            for name in os.listdir(BASE_DIR):
                if "env" in name.lower():
                    path = os.path.join(BASE_DIR, name)
                    # Attempt to load as .env format
                    load_dotenv(dotenv_path=path, override=True)
                    if os.getenv("DEEPSEEK_API_KEY"):
                        break
        except Exception:
            # best-effort; ignore parsing errors
            pass


_ensure_env_loaded()


@dataclass
class DeepSeekConfig:
    api_key: str
    base_url: str = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
    model: str = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")


def create_app() -> Flask:
    app = Flask(__name__, template_folder="templates", static_folder="static")
    threads: Dict[str, List[Dict[str, str]]] = {}

    def deepseek_chat(messages: List[Dict[str, str]], temperature: float = 0.3, model_override: str | None = None) -> str:
        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 无密钥返回演示
            user_last = next((m["content"] for m in reversed(messages) if m.get("role") == "user"), "")
            return (
                "[演示回答] 当前未连接 DeepSeek，大模型功能处于示例模式。\n"
                f"你的问题: {user_last}"
            )
        url = f"{cfg.base_url.rstrip('/')}/chat/completions"
        resp = requests.post(
            url,
            headers={
                "Authorization": f"Bearer {cfg.api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": model_override or cfg.model,
                "messages": messages,
                "temperature": temperature,
            },
            timeout=30,
        )
        resp.raise_for_status()
        data = resp.json()
        return data.get("choices", [{}])[0].get("message", {}).get("content", "")

    @app.route("/")
    def index() -> Any:
        return render_template("patient_index.html")

    @app.route("/ai_consult")
    def ai_consult() -> Any:
        return render_template("ai_consult_center.html")
    
    @app.route("/ai_demo")
    def ai_demo() -> Any:
        """AI功能演示页面"""
        with open("ai_demo.html", "r", encoding="utf-8") as f:
            return f.read()

    @app.post("/api/book")
    def api_book() -> Any:
        data: Dict[str, Any] = request.get_json(silent=True) or {}
        hospital = data.get("hospital", "示例医院")
        dept = data.get("dept")
        doctor = data.get("doctor")
        slot = data.get("slot")
        if not (dept and doctor and slot):
            return jsonify({"ok": False, "error": "缺少必要字段：科室/医生/时段"}), 400
        booking_id = f"BK-{uuid.uuid4().hex[:8].upper()}"
        return jsonify({
            "ok": True,
            "booking_id": booking_id,
            "ticket": {
                "hospital": hospital,
                "dept": dept,
                "doctor": doctor,
                "slot": slot,
            }
        })

    @app.post("/api/ai")
    def api_ai() -> Any:
        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 无密钥时返回演示回答，便于前端联调与用户感知
            demo = (
                "[演示回答] 已收到你的问题，我目前未连接真实大模型。\n"
                "请在服务器环境设置 DEEPSEEK_API_KEY 后重启：\n"
                "Windows PowerShell 示例：$env:DEEPSEEK_API_KEY=\"你的密钥\""
            )
            payload: Dict[str, Any] = request.get_json(silent=True) or {}
            q = (payload.get("question", "").strip())
            return jsonify({"ok": True, "answer": f"{demo}\n\n你的问题: {q}"})
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        question: str = payload.get("question", "").strip()
        context: str = payload.get("context", "")
        if not question:
            return jsonify({"ok": False, "error": "问题为空"}), 400

        try:
            # OpenAI-compatible Chat Completions API
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位资深导诊与健康助理，回答要清晰、可操作，并避免诊断。"},
                        {"role": "user", "content": f"上下文: {context}\n问题: {question}"},
                    ],
                    "temperature": 0.3,
                    "stream": False,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            return jsonify({"ok": True, "answer": content})
        except requests.HTTPError as e:
            try:
                detail = e.response.json()
            except Exception:  # noqa: BLE001
                detail = {"message": str(e)}
            return jsonify({"ok": False, "error": "DeepSeek HTTP 错误", "detail": detail}), 502
        except Exception as e:  # noqa: BLE001
            return jsonify({"ok": False, "error": f"AI 调用异常: {e}"}), 500

    @app.post("/api/ai_chat")
    def api_ai_chat() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        thread_id = payload.get("thread_id") or f"T-{uuid.uuid4().hex[:8]}"
        message = (payload.get("message") or "").strip()
        model = (payload.get("model") or "").strip() or None
        temperature = float(payload.get("temperature") or 0.3)
        if not message:
            return jsonify({"ok": False, "error": "消息为空"}), 400
        history = threads.setdefault(thread_id, [])
        if not history:
            history.append({"role": "system", "content": "你是一位资深导诊与健康助理，回答简洁、可操作，避免确诊与用药指导。"})
        history.append({"role": "user", "content": message})
        try:
            answer = deepseek_chat(history, temperature=temperature, model_override=model)
            history.append({"role": "assistant", "content": answer})
            return jsonify({"ok": True, "thread_id": thread_id, "answer": answer})
        except requests.HTTPError as e:
            return jsonify({"ok": False, "error": f"DeepSeek 错误: {e}"}), 502
    @app.post("/api/ai_chat_stream")
    def api_ai_chat_stream() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        thread_id = payload.get("thread_id") or f"T-{uuid.uuid4().hex[:8]}"
        message = (payload.get("message") or "").strip()
        model = (payload.get("model") or "").strip() or None
        temperature = float(payload.get("temperature") or 0.3)
        if not message:
            return jsonify({"ok": False, "error": "消息为空"}), 400

        history = threads.setdefault(thread_id, [])
        if not history:
            history.append({"role": "system", "content": "你是一位资深导诊与健康助理，回答简洁、可操作，避免确诊与用药指导。"})
        history.append({"role": "user", "content": message})

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # Demo流式：逐字符发送
            demo = "[演示流] 未连接 DeepSeek，将在配置密钥后提供真实流式回复。"
            def gen_demo():
                yield f"data: {{\"thread_id\": \"{thread_id}\", \"delta\": \"\"}}\n\n"
                for ch in demo:
                    yield f"data: {{\"delta\": \"{ch}\"}}\n\n"
                yield "data: [DONE]\n\n"
            return Response(stream_with_context(gen_demo()), mimetype="text/event-stream")

        def event_stream():
            try:
                url = f"{cfg.base_url.rstrip('/')}/chat/completions"
                resp = requests.post(
                    url,
                    headers={
                        "Authorization": f"Bearer {cfg.api_key}",
                        "Content-Type": "application/json",
                    },
                    json={
                        "model": model or cfg.model,
                        "messages": history,
                        "temperature": temperature,
                        "stream": True,
                    },
                    timeout=30,
                    stream=True,
                )
                resp.raise_for_status()
                
                # 发送初始消息
                yield f"data: {{\"thread_id\": \"{thread_id}\", \"delta\": \"\"}}\n\n"
                
                # 处理流式响应
                full_content = ""
                for line in resp.iter_lines():
                    if line:
                        line = line.decode('utf-8')
                        if line.startswith('data: '):
                            data_str = line[6:]  # 移除 "data: " 前缀
                            if data_str.strip() == '[DONE]':
                                history.append({"role": "assistant", "content": full_content})
                                yield "data: [DONE]\n\n"
                                break
                            try:
                                import json
                                data = json.loads(data_str)
                                delta = data.get("choices", [{}])[0].get("delta", {})
                                content = delta.get("content", "")
                                if content:
                                    full_content += content
                                    yield f"data: {{\"delta\": {json.dumps(content)}}}\n\n"
                            except Exception:
                                pass
            except Exception as e:
                print(f"Event stream error: {e}")
                yield f"data: {{\"error\": \"{str(e)}\"}}\n\n"
        
        return Response(stream_with_context(event_stream()), mimetype="text/event-stream")

    # 新增API端点：AI智能分诊
    @app.post("/api/triage")
    def api_triage() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        symptoms: str = payload.get("symptoms", "").strip()
        if not symptoms:
            return jsonify({"ok": False, "error": "症状描述为空"}), 400

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的分诊逻辑
            return jsonify({
                "ok": True,
                "department": "内科",
                "candidates": ["感冒", "上呼吸道感染", "流感"],
                "ai": "根据症状描述，建议您前往内科就诊。如有发热、咳嗽加重，请及时就医。"
            })

        try:
            # 调用大模型进行智能分诊
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位专业的医疗分诊助手。根据患者描述的症状，推荐最合适的就诊科室，并提供2-3个可能的健康问题。回答要简洁、准确，避免确诊性语言。"},
                        {"role": "user", "content": f"症状描述：{symptoms}"},
                    ],
                    "temperature": 0.2,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            # 解析大模型返回的内容，提取科室和可能的健康问题
            # 这里使用简化的逻辑，实际应用中可能需要更复杂的解析
            department = "内科"  # 默认值
            candidates = ["待确认"]  # 默认值
            
            # 简单的关键词匹配，实际应用中可能需要更复杂的NLP处理
            if "内科" in content:
                department = "内科"
            elif "外科" in content:
                department = "外科"
            elif "儿科" in content:
                department = "儿科"
            elif "妇产科" in content:
                department = "妇产科"
            elif "皮肤科" in content:
                department = "皮肤科"
            elif "眼科" in content:
                department = "眼科"
            elif "耳鼻喉科" in content:
                department = "耳鼻喉科"
            elif "口腔科" in content:
                department = "口腔科"
            
            return jsonify({
                "ok": True,
                "department": department,
                "candidates": candidates,
                "ai": content
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"分诊失败: {e}"}), 500

    # 新增API端点：AI报告解读
    @app.post("/api/report_explain")
    def api_report_explain() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        report_text: str = payload.get("text", "").strip()
        if not report_text:
            return jsonify({"ok": False, "error": "报告内容为空"}), 400

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的报告解读
            return jsonify({
                "ok": True,
                "hints": [
                    "报告显示血常规基本正常",
                    "建议定期复查",
                    "如有不适请及时就医"
                ],
                "ai": "您的检查报告总体情况良好，各项指标在正常范围内。建议保持健康的生活方式，定期进行体检。如有任何不适症状，请及时咨询医生。"
            })

        try:
            # 调用大模型进行报告解读
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位专业的医学报告解读助手。请用通俗易懂的语言解释检查报告，提取关键信息和异常指标，提供健康建议。避免使用专业术语，不要做出确诊性结论。"},
                        {"role": "user", "content": f"请解读以下医疗报告：\n{report_text}"},
                    ],
                    "temperature": 0.2,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            # 提取关键提示信息
            hints = ["报告解读完成，请查看详细说明"]
            
            return jsonify({
                "ok": True,
                "hints": hints,
                "ai": content
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"报告解读失败: {e}"}), 500

    # 新增API端点：AI医生推荐
    @app.post("/api/doctor_reco")
    def api_doctor_reco() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        symptoms: str = payload.get("symptoms", "").strip()
        if not symptoms:
            return jsonify({"ok": False, "error": "症状描述为空"}), 400

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的医生推荐
            return jsonify({
                "ok": True,
                "dept": "内科",
                "doctors": [
                    {
                        "name": "张医生",
                        "title": "主任医师",
                        "dept": "内科",
                        "score": 4.9,
                        "hot": "热门",
                        "slots": ["周一上午", "周三下午"],
                        "expertise": "呼吸系统疾病、感染性疾病"
                    },
                    {
                        "name": "李医生",
                        "title": "副主任医师",
                        "dept": "内科",
                        "score": 4.8,
                        "hot": "可约",
                        "slots": ["周二上午", "周五下午"],
                        "expertise": "心血管疾病、高血压"
                    }
                ]
            })

        try:
            # 调用大模型进行医生推荐分析
            # 这里简化处理，实际应用中可能需要结合医院的医生数据库
            # 演示返回模拟数据
            return jsonify({
                "ok": True,
                "dept": "内科",
                "doctors": [
                    {
                        "name": "王医生",
                        "title": "主任医师",
                        "dept": "内科",
                        "score": 4.9,
                        "hot": "热门",
                        "slots": ["周一上午", "周四下午"],
                        "expertise": "根据症状匹配的专家领域"
                    }
                ]
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"医生推荐失败: {e}"}), 500

    # 新增API端点：AI健康风险评估
    @app.post("/api/health_risk")
    def api_health_risk() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        age: int = payload.get("age", 0)
        gender: str = payload.get("gender", "")
        height: float = payload.get("height", 0)
        weight: float = payload.get("weight", 0)
        blood_pressure: str = payload.get("blood_pressure", "")
        blood_sugar: float = payload.get("blood_sugar", 0)
        habits: str = payload.get("habits", "")
        medical_history: str = payload.get("medical_history", "")

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的健康风险评估
            risk_level = "低"
            if age > 50:
                risk_level = "中"
            if "高血压" in medical_history or "糖尿病" in medical_history:
                risk_level = "中高"
            
            return jsonify({
                "ok": True,
                "risk_level": risk_level,
                "risks": ["心血管疾病风险", "代谢综合征风险"],
                "suggestions": ["保持健康饮食", "定期运动", "定期体检"],
                "ai": "根据您提供的信息，您的总体健康风险为" + risk_level + "。建议保持健康的生活方式，定期进行体检，如有不适及时就医。"
            })

        try:
            # 构建评估请求
            user_info = f"年龄：{age}岁\n性别：{gender}\n身高：{height}cm\n体重：{weight}kg\n血压：{blood_pressure}\n血糖：{blood_sugar}mmol/L\n生活习惯：{habits}\n既往病史：{medical_history}"
            
            # 调用大模型进行健康风险评估
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位专业的健康风险评估助手。根据用户提供的基本健康信息，评估可能的健康风险，并提供预防建议。回答要客观、专业，避免引起不必要的恐慌。"},
                        {"role": "user", "content": f"请根据以下信息进行健康风险评估：\n{user_info}"},
                    ],
                    "temperature": 0.2,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            return jsonify({
                "ok": True,
                "risk_level": "中",  # 简化返回，实际应从content中解析
                "risks": ["待评估"],
                "suggestions": ["待评估"],
                "ai": content
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"健康风险评估失败: {e}"}), 500

    # 新增API端点：AI用药指导
    @app.post("/api/medication_guide")
    def api_medication_guide() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        medications: List[str] = payload.get("medications", [])
        if not medications:
            return jsonify({"ok": False, "error": "药品列表为空"}), 400

        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的用药指导
            return jsonify({
                "ok": True,
                "interactions": ["无明显相互作用"],
                "precautions": ["请按医嘱服药", "注意药物保存条件"],
                "suggestions": ["餐后服用以减少胃部刺激", "用药期间避免饮酒"],
                "ai": "您提供的药物组合目前未发现明显相互作用。请按照医生的建议规律服药，注意观察用药后的反应，如有不适请及时咨询医生。"
            })

        try:
            # 构建用药指导请求
            meds_str = "、".join(medications)
            
            # 调用大模型进行用药指导
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位专业的用药指导助手。请分析药物之间可能的相互作用，提供用药注意事项和建议。避免做出确诊性结论，始终建议用户遵循医生的指导。"},
                        {"role": "user", "content": f"请分析以下药物组合的相互作用和用药建议：\n{meds_str}"},
                    ],
                    "temperature": 0.2,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            return jsonify({
                "ok": True,
                "interactions": ["待分析"],
                "precautions": ["待分析"],
                "suggestions": ["待分析"],
                "ai": content
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"用药指导失败: {e}"}), 500

    # 新增API端点：BMI计算
    @app.post("/api/calc/bmi")
    def api_calc_bmi() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        height_cm: float = payload.get("height_cm", 0)
        weight_kg: float = payload.get("weight_kg", 0)
        
        if height_cm <= 0 or weight_kg <= 0:
            return jsonify({"ok": False, "error": "身高和体重必须为正数"}), 400
        
        # 计算BMI
        height_m = height_cm / 100
        bmi = weight_kg / (height_m * height_m)
        
        # 判断BMI等级
        if bmi < 18.5:
            level = "偏瘦"
        elif bmi < 24:
            level = "正常"
        elif bmi < 28:
            level = "超重"
        else:
            level = "肥胖"
        
        return jsonify({
            "ok": True,
            "bmi": round(bmi, 1),
            "level": level
        })

    # 新增API端点：AI健康生活建议
    @app.post("/api/health_advice")
    def api_health_advice() -> Any:
        payload: Dict[str, Any] = request.get_json(silent=True) or {}
        health_goal: str = payload.get("goal", "").strip()
        current_status: str = payload.get("status", "").strip()
        
        if not health_goal:
            return jsonify({"ok": False, "error": "健康目标为空"}), 400
        
        cfg = DeepSeekConfig(api_key=os.getenv("DEEPSEEK_API_KEY", ""))
        if not cfg.api_key:
            # 演示模式下的健康建议
            return jsonify({
                "ok": True,
                "diet": ["均衡饮食", "多吃蔬菜水果", "控制盐分摄入"],
                "exercise": ["每周至少150分钟中等强度运动", "每天步行8000步"],
                "lifestyle": ["保持充足睡眠", "减少压力", "戒烟限酒"],
                "ai": "根据您的健康目标，建议您保持健康的生活方式，均衡饮食，适量运动，保持良好的心态，定期体检。"
            })

        try:
            # 构建健康建议请求
            request_content = f"健康目标：{health_goal}\n当前状况：{current_status}"
            
            # 调用大模型提供健康建议
            url = f"{cfg.base_url.rstrip('/')}/chat/completions"
            resp = requests.post(
                url,
                headers={
                    "Authorization": f"Bearer {cfg.api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": cfg.model,
                    "messages": [
                        {"role": "system", "content": "你是一位专业的健康生活顾问。根据用户的健康目标和当前状况，提供个性化的饮食、运动和生活方式建议。建议要具体、可行，避免过于笼统的指导。"},
                        {"role": "user", "content": f"请根据以下信息提供健康生活建议：\n{request_content}"},
                    ],
                    "temperature": 0.3,
                },
                timeout=30,
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            return jsonify({
                "ok": True,
                "diet": ["待分析"],
                "exercise": ["待分析"],
                "lifestyle": ["待分析"],
                "ai": content
            })
        except Exception as e:
            return jsonify({"ok": False, "error": f"健康建议生成失败: {e}"}), 500

    # === 患者端专用API补充 ===
    # 初始化内存数据存储
    bookings: List[Dict[str, Any]] = []
    results: Dict[str, Dict[str, Any]] = {}
    prescriptions: Dict[str, Dict[str, Any]] = {}
    health_records: Dict[str, Dict[str, Any]] = {}
    chronic_metrics: Dict[str, List[Dict[str, Any]]] = {}
    feedbacks: List[Dict[str, Any]] = []

    # 种子演示数据
    demo_user_id = "u_demo"
    results["rpt_1001"] = {
        "id": "rpt_1001",
        "userId": demo_user_id,
        "type": "血常规",
        "status": "已出报告",
        "time": "2025-10-30 09:30",
        "summary": "白细胞、红细胞、血红蛋白均在正常范围。",
        "images": [{"url": "https://dummyimage.com/800x400/667eea/ffffff&text=Report+Preview", "alt": "Report Preview"}]
    }
    prescriptions["rx_2001"] = {
        "id": "rx_2001",
        "userId": demo_user_id,
        "doctor": "李医生",
        "dept": "内分泌科",
        "date": "2025-10-29",
        "meds": [
            {"name": "二甲双胍片", "dose": "0.5g", "freq": "bid", "days": 14},
            {"name": "阿卡波糖", "dose": "50mg", "freq": "tid", "days": 14}
        ],
        "insurance": True
    }
    health_records[demo_user_id] = {
        "allergies": ["青霉素"],
        "medHistory": ["高血压"],
        "visitHistory": [{"date": "2025-10-15", "dept": "心内科", "reason": "胸闷"}],
        "lifestyle": {"exercise": "每周3次", "diet": "低盐低脂"}
    }
    chronic_metrics[demo_user_id] = [
        {"type": "blood_pressure", "systolic": 128, "diastolic": 82, "time": "2025-10-27 08:00"},
        {"type": "blood_pressure", "systolic": 132, "diastolic": 85, "time": "2025-10-28 08:00"},
        {"type": "blood_glucose", "value": 6.3, "time": "2025-10-28 07:30"}
    ]

    @app.post("/api/booking")
    def api_booking():
        payload = request.get_json(force=True)
        booking = {
            "id": f"bk_{len(bookings)+1:04d}",
            "hospital": payload.get("hospital", "示例医院"),
            "dept": payload.get("dept"),
            "doctor": payload.get("doctor"),
            "slot": payload.get("slot"),
            "createdAt": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        bookings.append(booking)
        return jsonify({"ok": True, "data": booking})

    @app.get("/api/results/<result_id>")
    def api_results_detail(result_id: str):
        data = results.get(result_id)
        if not data:
            return jsonify({"ok": False, "error": "not_found"}), 404
        return jsonify({"ok": True, "data": data})

    @app.get("/api/results")
    def api_results_list():
        return jsonify({"ok": True, "data": list(results.values())})

    @app.get("/api/prescriptions")
    def api_prescriptions():
        return jsonify({"ok": True, "data": list(prescriptions.values())})

    @app.get("/api/health-record/<user_id>")
    def api_health_record(user_id: str):
        return jsonify({"ok": True, "data": health_records.get(user_id, {})})

    @app.post("/api/chronic/record")
    def api_chronic_record():
        payload = request.get_json(force=True)
        user_id = payload.get("userId", demo_user_id)
        metric = payload.get("metric")
        if not metric:
            return jsonify({"ok": False, "error": "invalid_metric"}), 400
        chronic_metrics.setdefault(user_id, []).append(metric)
        return jsonify({"ok": True})

    @app.get("/api/chronic/metrics/<user_id>")
    def api_chronic_metrics(user_id: str):
        return jsonify({"ok": True, "data": chronic_metrics.get(user_id, [])})

    @app.post("/api/consult")
    def api_consult():
        payload = request.get_json(force=True)
        message = payload.get("message", "")
        history = payload.get("history", [])
        reply = generate_consultation_reply(message, history)
        return jsonify({"ok": True, "reply": reply})

    @app.get("/api/education")
    def api_education():
        articles = [
            {"title": "秋冬季心血管保健指南", "link": "https://example.org/edu/heart"},
            {"title": "糖尿病饮食要点", "link": "https://example.org/edu/diabetes"},
            {"title": "流感季节防护建议", "link": "https://example.org/edu/flu"}
        ]
        return jsonify({"ok": True, "data": articles})

    @app.post("/api/pay")
    def api_pay():
        payload = request.get_json(force=True)
        amount = payload.get("amount", 0)
        method = payload.get("method", "医保")
        return jsonify({
            "ok": True,
            "status": "paid",
            "amount": amount,
            "method": method,
            "tradeNo": f"TRADE{datetime.now().strftime('%Y%m%d%H%M%S')}"
        })

    @app.get("/api/navigation")
    def api_navigation():
        return jsonify({
            "ok": True,
            "data": {
                "hospital": "示例医院总院",
                "address": "XX市XX区健康路100号",
                "mapIframe": "https://www.amap.com/iframe.html"
            }
        })

    @app.post("/api/feedback")
    def api_feedback():
        payload = request.get_json(force=True)
        item = {
            "score": int(payload.get("score", 5)),
            "content": payload.get("content", ""),
            "createdAt": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        feedbacks.append(item)
        return jsonify({"ok": True})

    return app


app = create_app()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.getenv("PORT", "5000")), debug=True)


